<template>
  <div class="profile-page">
    <div class="page-header">
      <div class="container">
        <h1 class="page-title">个人中心</h1>
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/portal' }">首页</el-breadcrumb-item>
          <el-breadcrumb-item>个人中心</el-breadcrumb-item>
        </el-breadcrumb>
      </div>
    </div>
    
    <div class="container main-content">
      <el-row :gutter="20">
        <!-- 左侧个人信息卡片 -->
        <el-col :xs="24" :sm="24" :md="8" :lg="6" :xl="6">
          <div class="user-card">
            <div class="user-avatar">
              <el-avatar :size="100" :src="userAvatar">
                {{ userStore.name?.charAt(0) || userStore.username?.charAt(0) || 'U' }}
              </el-avatar>
            </div>
            <h2 class="user-name">{{ userStore.name || userStore.username }}</h2>
            <p class="user-role">{{ roleDisplay }}</p>
            <div class="user-stats">
              <div class="stat-item">
                <div class="stat-value">{{ patientStats.appointments || 0 }}</div>
                <div class="stat-label">预约数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ patientStats.visits || 0 }}</div>
                <div class="stat-label">就诊数</div>
              </div>
              <div class="stat-item">
                <div class="stat-value">{{ patientStats.reports || 0 }}</div>
                <div class="stat-label">报告数</div>
              </div>
            </div>
          </div>
        </el-col>
        
        <!-- 右侧信息和设置 -->
        <el-col :xs="24" :sm="24" :md="16" :lg="18" :xl="18">
          <el-tabs>
            <!-- 个人资料标签页 -->
            <el-tab-pane label="个人资料">
              <el-card class="info-card">
                <template #header>
                  <div class="card-header">
                    <span>基本信息</span>
                    <el-button type="primary" @click="editMode = !editMode">
                      {{ editMode ? '取消编辑' : '编辑信息' }}
                    </el-button>
                  </div>
                </template>
                
                <el-form 
                  :model="userForm" 
                  :rules="userRules" 
                  ref="userFormRef"
                  label-width="100px"
                  :disabled="!editMode"
                >
                  <el-form-item label="用户名" prop="username">
                    <el-input v-model="userForm.username" disabled></el-input>
                  </el-form-item>
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="userForm.name"></el-input>
                  </el-form-item>
                  <el-form-item label="性别" prop="gender">
                    <el-select v-model="userForm.gender" placeholder="请选择">
                      <el-option label="男" value="男"></el-option>
                      <el-option label="女" value="女"></el-option>
                      <el-option label="其他" value="其他"></el-option>
                      <el-option label="未知" value="未知"></el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="手机号码" prop="phone">
                    <el-input v-model="userForm.phone"></el-input>
                  </el-form-item>
                  <el-form-item label="电子邮箱" prop="email">
                    <el-input v-model="userForm.email"></el-input>
                  </el-form-item>
                  <el-form-item label="出生日期" prop="birthday" v-if="userStore.userRole === 'patient'">
                    <el-date-picker 
                      v-model="userForm.birthday" 
                      type="date" 
                      placeholder="选择日期"
                      format="YYYY-MM-DD"
                    ></el-date-picker>
                  </el-form-item>
                  <el-form-item v-if="editMode">
                    <el-button type="primary" @click="updateUserInfo">保存信息</el-button>
                    <el-button @click="resetForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>
            
            <!-- 安全设置标签页 -->
            <el-tab-pane label="安全设置">
              <el-card class="info-card">
                <template #header>
                  <div class="card-header">
                    <span>修改密码</span>
                  </div>
                </template>
                
                <el-form 
                  :model="passwordForm" 
                  :rules="passwordRules" 
                  ref="passwordFormRef"
                  label-width="120px"
                >
                  <el-form-item label="当前密码" prop="oldPassword">
                    <el-input 
                      v-model="passwordForm.oldPassword" 
                      type="password" 
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="新密码" prop="newPassword">
                    <el-input 
                      v-model="passwordForm.newPassword" 
                      type="password" 
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="确认新密码" prop="confirmPassword">
                    <el-input 
                      v-model="passwordForm.confirmPassword" 
                      type="password" 
                      show-password
                    ></el-input>
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="changePassword">修改密码</el-button>
                    <el-button @click="resetPasswordForm">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-card>
            </el-tab-pane>
          </el-tabs>
        </el-col>
      </el-row>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { userAPI, patientAPI, authAPI } from '@/utils/api'

const router = useRouter()
const userStore = useUserStore()
const editMode = ref(false)
const userFormRef = ref(null)
const passwordFormRef = ref(null)

// 用户头像
const userAvatar = computed(() => {
  return userStore.avatar || ''
})

// 角色展示文本
const roleDisplay = computed(() => {
  const roleMap = {
    'admin': '管理员',
    'doctor': '医生',
    'nurse': '护士',
    'patient': '患者',
    'user': '普通用户'
  }
  return roleMap[userStore.userRole] || '用户'
})

// 用户表单数据
const userForm = reactive({
  username: '',
  name: '',
  gender: '',
  phone: '',
  email: '',
  birthday: ''
})

// 密码表单数据
const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 统计数据
const patientStats = reactive({
  appointments: 0,
  visits: 0,
  reports: 0
})

// 表单验证规则
const userRules = {
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

const passwordRules = {
  oldPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入新密码', trigger: 'blur' },
    { 
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      }, 
      trigger: 'blur' 
    }
  ]
}

// 组件挂载时
onMounted(() => {
  // 检查用户是否登录
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/portal/login')
    return
  }
  
  // 根据角色重定向到相应的个人中心页面
  if (userStore.userRole === 'doctor') {
    router.replace('/portal/doctor/profile')
    return
  } else if (userStore.userRole === 'admin') {
    router.replace('/portal/admin/profile')
    return
  } else if (userStore.userRole === 'patient') {
    router.replace('/portal/patient/profile')
    return
  }
  
  // 获取用户信息
  loadUserDetailInfo()
  
  // 获取患者统计数据
  loadUserStats()
})

// 加载用户详细信息
const loadUserDetailInfo = async () => {
  try {
    // 从API获取当前用户的详细信息
    const userId = userStore.userInfo.id || userStore.userInfo._id
    if (!userId) {
      console.error('无法获取用户ID')
      loadUserInfoFromStore() // 回退到从store加载
      return
    }
    
    // 调用API获取详细信息
    const response = await userAPI.getUser(userId)
    if (response.success && response.data && response.data.user) {
      const userData = response.data.user
      console.log('获取到用户详细信息:', userData)
      
      // 使用API返回的详细信息更新表单
      userForm.username = userData.username || ''
      userForm.name = userData.name || ''
      
      // 处理性别字段 - 确保使用中文值
      let gender = userData.personalInfo?.gender || userData.gender || ''
      if (gender === 'male') gender = '男'
      else if (gender === 'female') gender = '女'
      else if (gender === 'other') gender = '其他'
      else if (!['男', '女', '其他', '未知'].includes(gender)) gender = '未知'
      userForm.gender = gender
      
      userForm.phone = userData.phone || ''
      userForm.email = userData.email || ''
      
      // 处理生日字段 - 患者从patient对象获取birthDate，其他角色不显示
      if (userStore.userRole === 'patient') {
        // 尝试从不同位置获取生日信息
        const birthDate = userData.patient?.birthDate || userData.birthDate || userData.birthday || ''
        userForm.birthday = birthDate ? new Date(birthDate) : ''
      } else {
        userForm.birthday = ''
      }
      
      // 更新store中的用户信息，确保其他地方使用的也是最新的
      userStore.setUserInfo({
        ...userStore.userInfo,
        ...userData
      })
    } else {
      console.warn('获取用户详情失败，使用本地store数据')
      loadUserInfoFromStore() // 回退到从store加载
    }
  } catch (error) {
    console.error('加载用户详细信息失败', error)
    loadUserInfoFromStore() // 回退到从store加载
  }
}

// 从store加载用户信息（作为备用方案）
const loadUserInfoFromStore = () => {
  const user = userStore.userInfo
  
  // 填充表单数据
  userForm.username = user.username || ''
  userForm.name = user.name || ''
  
  // 处理性别字段 - 确保使用中文值
  let gender = user.personalInfo?.gender || user.gender || ''
  if (gender === 'male') gender = '男'
  else if (gender === 'female') gender = '女'
  else if (gender === 'other') gender = '其他'
  else if (!['男', '女', '其他', '未知'].includes(gender)) gender = '未知'
  userForm.gender = gender
  
  userForm.phone = user.phone || ''
  userForm.email = user.email || ''
  
  // 处理生日字段 - 患者从patient对象获取birthDate，其他角色不显示
  if (userStore.userRole === 'patient') {
    // 尝试从不同位置获取生日信息
    const birthDate = user.patient?.birthDate || user.birthDate || user.birthday || ''
    userForm.birthday = birthDate ? new Date(birthDate) : ''
  } else {
    userForm.birthday = ''
  }
}

// 加载统计数据
const loadUserStats = async () => {
  try {
    // 实际项目中应该调用API获取统计数据
    // 获取用户ID
    const userId = userStore.userInfo.id || userStore.userInfo._id
    if (!userId) {
      console.error('无法获取用户ID，使用默认统计数据')
      patientStats.appointments = 3
      patientStats.visits = 5
      patientStats.reports = 2
      return
    }
    
    // 这里可以调用相关API获取真实数据
    // 如: const response = await appointmentAPI.getUserAppointmentStats(userId)
    // 由于目前没有现成的API，使用模拟数据
    patientStats.appointments = 3
    patientStats.visits = 5
    patientStats.reports = 2
  } catch (error) {
    console.error('加载统计数据失败', error)
    // 发生错误时设置默认值
    patientStats.appointments = 0
    patientStats.visits = 0
    patientStats.reports = 0
  }
}

// 更新用户信息
const updateUserInfo = async () => {
  if (!userFormRef.value) return
  
  try {
    await userFormRef.value.validate()
    
    const userId = userStore.userInfo.id || userStore.userInfo._id
    if (!userId) {
      ElMessage.error('无法获取用户ID，更新失败')
      return
    }
    
    // 准备要更新的数据 - 确保与后端schema完全匹配
    const updateData = {}
    
    // 只添加已修改且有值的字段
    if (userForm.name) updateData.name = userForm.name
    if (userForm.email) updateData.email = userForm.email
    if (userForm.phone) {
      // 验证手机号格式
      if (!/^\d{11}$/.test(userForm.phone)) {
        ElMessage.warning('手机号格式不正确，请输入11位数字')
        return
      }
      updateData.phone = userForm.phone
    }
    
    // 处理性别字段 - 只放在personalInfo对象中
    if (userForm.gender) {
      // 检查性别值是否符合枚举限制
      const validGenders = ['男', '女', '其他', '未知']
      if (!validGenders.includes(userForm.gender)) {
        ElMessage.warning(`性别值必须是以下之一: ${validGenders.join(', ')}`)
        return
      }
      
      // 创建personalInfo对象
      updateData.personalInfo = {
        gender: userForm.gender
      }
      
      // 保留用户其他personalInfo字段
      if (userStore.userInfo && userStore.userInfo.personalInfo) {
        const currentPersonalInfo = userStore.userInfo.personalInfo
        if (currentPersonalInfo.title) {
          updateData.personalInfo.title = currentPersonalInfo.title
        }
        if (currentPersonalInfo.specialties && Array.isArray(currentPersonalInfo.specialties)) {
          updateData.personalInfo.specialties = [...currentPersonalInfo.specialties]
        }
      }
    }
    
    // 处理生日字段 - 只有患者角色才有生日字段
    if (userForm.birthday && userStore.userRole === 'patient') {
      try {
        if (userForm.birthday instanceof Date) {
          const formattedDate = userForm.birthday.toISOString().split('T')[0]
          // 对于患者，我们需要使用患者API保存生日信息
          // 暂存生日信息，稍后使用patientAPI更新
          updateData.birthDate = formattedDate
        } else if (typeof userForm.birthday === 'string') {
          // 如果已经是字符串格式
          updateData.birthDate = userForm.birthday
        }
      } catch (error) {
        console.error('处理生日日期时出错:', error)
        ElMessage.warning('生日日期格式不正确')
        return
      }
    }
    
    console.log('准备更新用户数据:', JSON.stringify(updateData, null, 2))
    
    try {
      let response;
      
      // 判断用户角色，对患者使用不同的API
      if (userStore.userRole === 'patient') {
        // 1. 首先更新用户基本信息
        const userResponse = await userAPI.updateUser(userId, {
          name: updateData.name,
          email: updateData.email,
          phone: updateData.phone,
          personalInfo: updateData.personalInfo
        })
        
        // 2. 如果用户信息更新成功，再更新患者特有信息
        if (userResponse && userResponse.success) {
          // 寻找患者ID
          const patientId = userStore.userInfo.patientId || userStore.userInfo.patient?.id
          
          if (patientId && updateData.birthDate) {
            // 只传递患者API所需的数据
            const patientUpdateData = {
              name: updateData.name,
              birthDate: updateData.birthDate
            }
            
            // 更新患者信息
            const patientResponse = await patientAPI.updatePatient(patientId, patientUpdateData)
            
            // 合并两个API的响应结果
            response = {
              success: userResponse.success && (patientResponse?.success !== false),
              message: patientResponse?.message || userResponse.message,
              data: {
                ...userResponse.data,
                patient: patientResponse?.data
              }
            }
          } else {
            response = userResponse
          }
        } else {
          response = userResponse
        }
      } else {
        // 非患者角色，直接使用用户API
        // 移除birthDate字段，防止验证错误
        if (updateData.birthDate) {
          delete updateData.birthDate
        }
        
        response = await userAPI.updateUser(userId, updateData)
      }
      
      console.log('API响应:', response)
      
      if (response && response.success) {
        // 更新本地store中的信息
        const updatedUser = { 
          ...userStore.userInfo,
          ...updateData
        }
        
        // 特殊处理嵌套对象，确保正确合并
        if (updateData.personalInfo) {
          updatedUser.personalInfo = {
            ...(userStore.userInfo.personalInfo || {}),
            ...updateData.personalInfo
          }
        }
        
        // 如果是患者，更新生日信息
        if (userStore.userRole === 'patient' && updateData.birthDate) {
          if (!updatedUser.patient) updatedUser.patient = {}
          updatedUser.patient.birthDate = updateData.birthDate
          updatedUser.birthDate = updateData.birthDate
        }
        
        userStore.setUserInfo(updatedUser)
        
        ElMessage.success('个人信息更新成功')
        editMode.value = false
        
        // 重新加载用户信息，确保显示最新数据
        loadUserDetailInfo()
      } else {
        // 如果是标准错误响应格式
        if (response && response.message) {
          ElMessage.error(response.message)
        } else {
          ElMessage.error('更新失败，请稍后重试')
        }
        
        // 如果有详细的验证错误信息
        if (response && response.errors) {
          console.error('验证错误详情:', response.errors)
          
          // 检查是否有未知字段的错误（如birthday）
          const unknownFields = Object.keys(response.errors).filter(field => 
            field !== 'personalInfo' && 
            !['username', 'password', 'email', 'phone', 'name', 'staffId', 'departmentId', 'role', 'roles', 'status'].includes(field)
          )
          
          if (unknownFields.length > 0) {
            console.warn('发现未知字段:', unknownFields)
            ElMessage.warning(`后端不支持以下字段: ${unknownFields.join(', ')}`)
          }
        }
      }
    } catch (error) {
      console.error('API调用出错:', error)
      
      // 尝试从错误对象中提取详细信息
      if (error.data) {
        // 如果错误对象本身包含成功/失败标志和消息
        if (error.success === false && error.message) {
          ElMessage.error(error.message)
        } 
        // 如果有验证错误
        else if (error.data.errors) {
          const errors = error.data.errors
          console.error('验证错误详情:', errors)
          
          // 格式化错误信息
          const errorMessages = []
          
          // 处理personalInfo嵌套错误
          if (errors.personalInfo) {
            if (typeof errors.personalInfo === 'object') {
              Object.entries(errors.personalInfo).forEach(([field, msg]) => {
                errorMessages.push(`个人信息.${field}: ${msg}`)
              })
            } else {
              errorMessages.push(`个人信息: ${errors.personalInfo}`)
            }
          }
          
          // 处理其他字段错误
          Object.entries(errors).forEach(([field, msg]) => {
            if (field !== 'personalInfo') {
              errorMessages.push(`${field}: ${typeof msg === 'object' ? JSON.stringify(msg) : msg}`)
            }
          })
          
          // 显示错误信息
          if (errorMessages.length > 0) {
            ElMessage.error(`验证失败: ${errorMessages.join('; ')}`)
          } else {
            ElMessage.error('数据验证失败')
          }
        }
      } else {
        // 默认错误消息
        ElMessage.error('更新失败，请稍后重试')
      }
    }
  } catch (error) {
    console.error('表单验证失败', error)
    ElMessage.error('表单验证失败，请检查输入')
  }
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    await passwordFormRef.value.validate()
    
    // 调用修改密码API
    const response = await authAPI.changePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })
    
    if (response && response.success) {
      ElMessage.success('密码修改成功，请重新登录')
      // 清除登录状态
      userStore.logout()
      // 跳转到登录页
      router.push('/portal/login')
    } else {
      ElMessage.error((response && response.message) || '密码修改失败，请检查当前密码是否正确')
    }
  } catch (error) {
    console.error('修改密码失败', error)
    if (error.response && error.response.data) {
      ElMessage.error(error.response.data.message || '密码修改失败，请检查当前密码是否正确')
    } else {
      ElMessage.error('密码修改失败，请稍后重试')
    }
  }
}

// 重置用户表单
const resetForm = () => {
  userFormRef.value.resetFields()
  loadUserDetailInfo()
}

// 重置密码表单
const resetPasswordForm = () => {
  passwordFormRef.value.resetFields()
}
</script>

<style scoped>
.profile-page {
  background-color: #f5f7fa;
  min-height: 100vh;
  padding-bottom: 40px;
}

.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 0 20px;
}

.page-header {
  background-color: white;
  padding: 20px 0;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 30px;
}

.page-title {
  font-size: 24px;
  color: #333;
  margin: 0 0 10px;
}

.main-content {
  margin-bottom: 40px;
}

.user-card {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 30px;
  text-align: center;
  margin-bottom: 20px;
}

.user-avatar {
  margin-bottom: 15px;
}

.user-name {
  font-size: 20px;
  margin: 10px 0 5px;
  color: #333;
}

.user-role {
  color: #909399;
  font-size: 14px;
  margin-bottom: 20px;
}

.user-stats {
  display: flex;
  justify-content: space-around;
  margin-top: 20px;
  border-top: 1px solid #eee;
  padding-top: 20px;
}

.stat-item {
  text-align: center;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #409EFF;
}

.stat-label {
  font-size: 12px;
  color: #909399;
  margin-top: 5px;
}

.info-card {
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}

@media (max-width: 768px) {
  .user-card {
    margin-bottom: 30px;
  }
}
</style> 